package com.example.config;

import com.example.entity.JobEntity;
import com.example.repository.JobRepository;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JobRecoveryConfig implements CommandLineRunner {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(String... args) throws Exception {
        List<JobEntity> normalJobs = jobRepository.findByStatus("NORMAL");
        
        for (JobEntity jobEntity : normalJobs) {
            try {
                Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(jobEntity.getJobClass());
                JobDetail jobDetail = JobBuilder.newJob(jobClass)
                        .withIdentity(jobEntity.getJobName(), jobEntity.getJobGroup())
                        .withDescription(jobEntity.getDescription())
                        .build();

                CronTrigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity(jobEntity.getJobName(), jobEntity.getJobGroup())
                        .withSchedule(CronScheduleBuilder.cronSchedule(jobEntity.getCronExpression()))
                        .build();

                scheduler.scheduleJob(jobDetail, trigger);
            } catch (Exception e) {
                // 记录恢复失败的任务，但不影响其他任务的恢复
                e.printStackTrace();
            }
        }
    }
}